package main

import (
	"fmt"
	"sync"
)


/*
	使用 sync.WaitGroup等待任务结束
*/
func work(i int,w worker){
	count := 0
	for  n := range w.in {
		fmt.Printf("%d,%c\n",i,n)
		// 通知结束
		w.done()
		count++
		fmt.Printf("调的次数: %d \n",count)
	}

}
type worker struct {
	in chan int
	done func()
}

func createWorker(i int , wg *sync.WaitGroup) worker{
	// 初始化一个worker，done调用sync.WaitGroup的Done()方法通知结束
	worker := worker{
		in:		make(chan int),
		done: 	func() {
			wg.Done()
		},
	}
	go work(i,worker)
	return worker
}

func chanDemo(){
	var workers  [10]worker

	var wg sync.WaitGroup

	for i :=0; i<10; i++{
		workers[i] = createWorker(i,&wg)
	}

	// 将任务加进去
	wg.Add(20)

	/*往channel中发数据*/

	for i,worker := range workers{
		worker.in <- 'a'+i
	}

	for i,worker := range workers{
		worker.in <- 'A'+i
	}
	// 等待goroutine任务结束
	wg.Wait()


}


func main() {
	chanDemo()
}
